package com.permission_server.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.permission_server.entity.SysPermissionEntity;
import com.permission_server.entity.SysUserEntity;
import com.permission_server.service.SysPermissionService;
import com.permission_server.service.SysUserService;
import com.permission_server.util.RedisUtil;
import com.permission_server.util.responseUtil.ResponseEnum;
import com.permission_server.util.responseUtil.ResponseUtil;
import com.permission_server.util.stpInterface.StpInterfaceImpl;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/login")
@Api(tags = "登录接口")
public class LoginController {

    public static final String USER_INFO = "UserInfo:";

    static Jedis redis = RedisUtil.getRedis();

    @Autowired
    SysUserService sysUserService;

    @Autowired
    StpInterfaceImpl stpInterface;

    @Autowired
    SysPermissionService sysPermissionService;

    @ApiOperation(value = "用户登录", notes = "传入账号和密码")
    @ApiResponses({
            @ApiResponse(code = 43010, message = "登录成功"),
            @ApiResponse(code = 43009, message = "登录有效"),
            @ApiResponse(code = 43006, message = "账号或密码错误"),
    })
    @PostMapping("/doLogin")
    public ResponseUtil doLogin(@RequestBody SysUserEntity sysUser) {
        if (StpUtil.isLogin()) return ResponseUtil.setE(ResponseEnum.LOGIN_VALID);
        SysUserEntity one = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>()
                .eq(SysUserEntity::getAccount, sysUser.getAccount()));
        if (ObjectUtil.isEmpty(one) || !one.getPassword().equals(sysUser.getPassword()))
            return ResponseUtil.setE(ResponseEnum.LOGIN_INFO_ERROR);
        StpUtil.login(sysUser.getAccount());
        redis.select(2);
        redis.setex(USER_INFO.concat(sysUser.getAccount()), (int) StpUtil.getTokenTimeout(), JSON.toJSONString(one));


        stpInterface.getRoleList(one.getId(), StpUtil.getLoginType());
        stpInterface.getPermissionList(one.getId(), StpUtil.getLoginType());

        System.out.println("\033[32;4m" + "++++++++++++++++++++++++++++++" + "\033[0m");
        System.out.println("\033[32;4m" + "===>当前账号" + one.getAccount() + " 登录类型：" + StpUtil.getLoginType() + "\033[0m");
        System.out.println("\033[32;4m" + "===>当前账号的角色集合：" + StpUtil.getRoleList() + "\033[0m");
        System.out.println("\033[32;4m" + "===>当前账号的权限码集合：" + StpUtil.getPermissionList() + "\033[0m");
        System.out.println("\033[32;4m" + "++++++++++++++++++++++++++++++" + "\033[0m");

        List<SysPermissionEntity> permissionEntities = sysPermissionService.listByIds(StpUtil.getPermissionList());
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("satoken", StpUtil.getTokenValue());
        resultMap.put("routes", permissionEntities);
        return ResponseUtil.setE(ResponseEnum.LOGIN_SUCCESS).setData(resultMap);
    }

    @ApiOperation(value = "用户注册", notes = "传入账号和密码")
    @ApiResponses({
            @ApiResponse(code = 43011, message = "注册成功"),
            @ApiResponse(code = 43001, message = "账号已存在")
    })
    @PostMapping("/doRegister")
    public ResponseUtil doRegister(@RequestBody SysUserEntity sysUser) {
        SysUserEntity one = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>()
                .eq(SysUserEntity::getAccount, sysUser.getAccount()));
        if (ObjectUtil.isNotEmpty(one)) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("账号已存在");
        sysUser.setCreateTime(DateUtil.date());
        sysUser.setSalt(RandomUtil.randomString(6));
        sysUser.setUsername("系统账号");
        sysUserService.save(sysUser);
        return ResponseUtil.setE(ResponseEnum.REGISTER_SUCCESS);
    }

    @ApiOperation(value = "退出登录", notes = "无参数，直接调用")
    @GetMapping("/logout")
    public void logout() {
        String loginId = StpUtil.getLoginId().toString();
        redis.select(2);
        redis.del(USER_INFO.concat(loginId));
        StpUtil.logout();
    }

    /**
     * 使用：根据登录成功所缓存的用户基本信息，在缓存中获取
     * 目的：减少对当前登录用户基本的频繁访问
     * 缓存：缓存库在2号库，缓存路径 UserInfo:[用户登录ID]
     *
     * @return
     */
    public static SysUserEntity getCurrentLoginUserInfo() {
        redis.select(2);
        String path = LoginController.USER_INFO.concat(StpUtil.getLoginId().toString());
        String userInfo = redis.get(path);
        return JSONObject.parseObject(userInfo, SysUserEntity.class);
    }
}
